package com.yanqu.road.dao.impl.union;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.dao.impl.logic.ResultSetParseEntityManger;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.player.UserPatronsSkill;
import com.yanqu.road.entity.union.UnionConstruct;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UnionMemberDaoImpl extends TempDataObjectDao<UnionMember> {

	public void getUnionMemberMap(Map<String, Map<Long, UnionMember>> unionMemberMap, Map<Long, UnionMember> deleteMemberMap) {
		ResultSet rs = null;
		CallableStatement call = null;
		String sql = "SELECT * FROM t_u_union_member t1 LEFT JOIN t_u_patrons t2 ON t1.chamberPatronsId = t2.patronsId AND t1.userId = t2.userId LEFT JOIN " +
				"t_u_patrons_skill t3 ON t2.patronsId = t3.patronsId AND t2.userId = t3.userId";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareCall(sql);
			rs = call.executeQuery();
			while (rs.next()) {
				UnionMember data = parse(rs);
				if(!StringUtils.isNullOrEmpty(data.getUnionUid())){
					if(!unionMemberMap.containsKey(data.getUnionUid())){
						unionMemberMap.put(data.getUnionUid(), new ConcurrentHashMap<>());
					}
					if(!unionMemberMap.get(data.getUnionUid()).containsKey(data.getUserId())) {
						unionMemberMap.get(data.getUnionUid()).put(data.getUserId(), data);
					}
					if(rs.getInt("patronsId") > 0){
						data = unionMemberMap.get(data.getUnionUid()).get(data.getUserId());
						UserPatrons userPatrons = ResultSetParseEntityManger.initUserPatrons(rs);
						if(null == data.getChamberPatron()){
							data.setChamberPatron(userPatrons);
						}
						if(rs.getInt("skillId") > 0) {
							userPatrons = data.getChamberPatron();
							UserPatronsSkill userPatronsSkill = ResultSetParseEntityManger.initUserPatronsSkill(rs);
							if(!userPatrons.isContainsSkill(userPatronsSkill.getType(), userPatronsSkill.getSkillId())){
								userPatrons.addSkill(userPatronsSkill);
							}
						}
					}
				}else {
					if(!deleteMemberMap.containsKey(data.getUserId())) {
						deleteMemberMap.put(data.getUserId(), data);
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			getDb().closeConnection(call, rs);
		}
	}

	@Override
	protected boolean addData(UnionMember data) {
		PreparedStatement call = null;
		String sql = "INSERT INTO t_u_union_member(unionUid,userId,position,userBaseInfo,modifyTime,contribution,totalContribution,"
				+ "donateTimes,quitTime,unionConstructData,constructRewardIndexList,todayContribution,chamberPatronsId) VALUES "
				+ "(?,?,?,?,?,?,?,?,?,?,?,?,?)";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setString(i++, data.getUnionUid());
			call.setLong(i++, data.getUserId());
			call.setInt(i++, data.getPosition());
			call.setString(i++, data.getUserBaseInfoJsonStr());
			call.setLong(i++, data.getModifyTime());
			call.setLong(i++, data.getContribution());
			call.setLong(i++, data.getTotalContribution());
			call.setInt(i++, data.getDonateTimes());
			call.setLong(i++, data.getQuitTime());
			call.setString(i++, data.getUnionConstructMapJson());
			call.setString(i++, data.getConstructRewardIndexListString());
			call.setInt(i++, data.getTodayContribution());
			call.setInt(i++, data.getChamberPatronsId());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected boolean updateData(UnionMember data) {
		PreparedStatement call = null;
		String sql = "UPDATE t_u_union_member SET unionUid=?,position=?,userBaseInfo=?,modifyTime=?,contribution=?,"
				+ "totalContribution=?,donateTimes=?,quitTime=?,unionConstructData=?,constructRewardIndexList=?,todayContribution=?,"
				+ "chamberPatronsId=? WHERE userId=?";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setString(i++, data.getUnionUid());
			call.setInt(i++, data.getPosition());
			call.setString(i++, data.getUserBaseInfoJsonStr());
			call.setLong(i++, data.getModifyTime());
			call.setLong(i++, data.getContribution());
			call.setLong(i++, data.getTotalContribution());
			call.setInt(i++, data.getDonateTimes());
			call.setLong(i++, data.getQuitTime());
			call.setString(i++, data.getUnionConstructMapJson());
			call.setString(i++, data.getConstructRewardIndexListString());
			call.setInt(i++, data.getTodayContribution());
			call.setInt(i++, data.getChamberPatronsId());
			call.setLong(i++, data.getUserId());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected UnionMember parseData(ResultSet rs) throws SQLException {
		UnionMember data = new UnionMember();
		data.setUnionUid(rs.getString("unionUid"));
		data.setUserId(rs.getLong("userId"));
		data.setPosition(rs.getInt("position"));
		String baseUserInfoStr = rs.getString("userBaseInfo");
		if(null == baseUserInfoStr){
			baseUserInfoStr = "";
		}
		UserBaseInfo userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {});
		if(null != userBaseInfo) {
			data.setUserBaseInfo(userBaseInfo);
		}
		data.setModifyTime(rs.getLong("modifyTime"));
		data.setContribution(rs.getLong("contribution"));
		data.setTotalContribution(rs.getLong("totalContribution"));
		data.setDonateTimes(rs.getInt("donateTimes"));
		data.setQuitTime(rs.getLong("quitTime"));
		data.setTodayContribution(rs.getInt("todayContribution"));
		data.setChamberPatronsId(rs.getInt("chamberPatronsId"));
		data.setConstructRewardIndexList(StringUtils.stringToIntegerList(rs.getString("constructRewardIndexList"), ","));
		String unionConstructData = rs.getString("unionConstructData");
		Map<Integer, UnionConstruct> unionConstructMap = new ConcurrentHashMap<>();
		if(!StringUtils.isNullOrEmpty(unionConstructData)){
			unionConstructMap = JSON.parseObject(unionConstructData, new TypeReference<Map<Integer, UnionConstruct>>() {});
		}
		data.setUnionConstructMap(unionConstructMap);
		return data;
	}
}
